package com.javasoft.service.WJC.impl;

import com.javasoft.dao.WJC.ExamQuestionMappingRepository;
import com.javasoft.dao.WJC.StudentAnswerRepository;
import com.javasoft.dao.XGX.QuestionRepository;
import com.javasoft.entity.WJC.ExamQuestionMapping;
import com.javasoft.entity.WJC.StudentAnswer;
import com.javasoft.entity.XGX.Question;
import com.javasoft.service.WJC._interface.JudgeService;
import com.javasoft.service.WJC._interface.PaperRuleService;
import com.javasoft.service.XGX.impl.WrongTableImpl;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service("judgeService")
public class JudgeServiceImpl implements JudgeService {

    private final StudentAnswerRepository studentAnswerRepository;
    @Getter
    private final QuestionRepository questionRepository;
    @Autowired
    private PaperRuleService paperRuleService;
    @Autowired
    private ExamQuestionMappingRepository examQuestionMappingRepository;
    @Autowired
    private WrongTableImpl wrongTableImpl;

    @Autowired
    public JudgeServiceImpl(StudentAnswerRepository studentAnswerRepository, QuestionRepository questionRepository) {
        this.studentAnswerRepository = studentAnswerRepository;
        this.questionRepository = questionRepository;
    }

    @Override
    public List<StudentAnswer> correctExam(Long examId){
        List<StudentAnswer> studentAnswers = studentAnswerRepository.findByExamId(examId);
        for(StudentAnswer studentAnswer : studentAnswers){
            studentAnswer.setTotalScore(calculateAndUpdateScore(examId,studentAnswer));
            studentAnswerRepository.save(studentAnswer);
        }
        // 使用最终计算的总分创建并返回批改结果
        return studentAnswers;
    }

    @Override
    public StudentAnswer correctExam(Long examId, Long studentId) {
        StudentAnswer studentAnswer = studentAnswerRepository.findByExamIdAndStudentId(examId, studentId);
        studentAnswer.setTotalScore(calculateAndUpdateScore(examId,studentAnswer));
        studentAnswerRepository.save(studentAnswer);
        // 使用最终计算的总分创建并返回批改结果
        return studentAnswer;
    }

    public List<String> getAnswersByExamId(Long examId) {
        // 获取考试中所有题目的映射
        List<ExamQuestionMapping> mappings = examQuestionMappingRepository.findByExamId(examId);

        // 提取所有题目的ID
        List<Long> questionIds = mappings.stream()
                .map(ExamQuestionMapping::getId)
                .collect(Collectors.toList());

        // 使用问题ID查询问题实体，获取答案
        List<Question> questions = questionRepository.findAllById(questionIds);

        // 构建答案列表

        return questions.stream()
                .map(Question::getAns)
                .collect(Collectors.toList());
    }
    private int calculateAndUpdateScore(Long examId, StudentAnswer studentAnswers) {
        // 参数合法性校验，避免传入null导致后续问题
        if (studentAnswers == null) {
            log.error("传入的学生答案对象为null，examId: {}", examId);
            throw new IllegalArgumentException("学生答案对象不能为null");
        }

        // 获取试卷总分和题目总数
        int scorePerQuestion = paperRuleService.getScoreByExamId(examId);
        int totalQuestions = paperRuleService.getNumByExamId(examId);
        List<String> rightAns = getAnswersByExamId(examId);
        List<Long> questionIds = getquestionIdsByExamId(examId);
        int totalScore = 0;


        for (int i = 0; i < totalQuestions; i++) {
            try {
               Long questionId = questionIds.get(i);

                // 根据索引构建对应的字段名
                String fieldName = "ans" + (i + 1);
                Field field = studentAnswers.getClass().getDeclaredField(fieldName);
                field.setAccessible(true);
                String stuAns = (String) field.get(studentAnswers);
                String correctAnswer = rightAns.get(i);

                // 构建对应judge属性的字段名，假设judge属性命名格式为judge + 题目序号（从1开始）
                String judgeFieldName = "judge" + (i + 1);
                Field judgeField = studentAnswers.getClass().getDeclaredField(judgeFieldName);
                judgeField.setAccessible(true);

                // 比较学生答案与正确答案（这里以严格相等为例，根据需要调整）
                if (stuAns!= null && stuAns.equals(correctAnswer)) {
                    judgeField.set(studentAnswers, 1); // 答案正确时设置对应judge属性为1
                    totalScore += scorePerQuestion;
                } else {
                    judgeField.set(studentAnswers, 0); // 答案错误时设置对应judge属性为0
                    wrongTableImpl.saveOrUpdateById(questionId);
                }
            } catch (NoSuchFieldException | IllegalAccessException e) {
                log.error("获取学生答案或设置judge属性时出现异常，examId: {}, questionIndex: {}", examId, i);
            }
        }
        return totalScore;
    }

    private List<Long> getquestionIdsByExamId(Long examId) {
        // 获取考试中所有题目的映射
        List<ExamQuestionMapping> mappings = examQuestionMappingRepository.findByExamId(examId);

        // 提取所有题目的ID
        List<Long> questionIds = mappings.stream()
                .map(ExamQuestionMapping::getId)
                .collect(Collectors.toList());
        return questionIds;
    }

}